<?php
/**
 * Created by PhpStorm.
 * User: chen
 * Date: 2016/1/14
 * Time: 16:26
 */
/**
 * 扫码核销卡券入口
 */
class ConsumeCardAction extends Action{
    public function _initialize(){
        import('ORG.Util.Session');
    }
    /**
     * 公共弹框方法
     */
    public function simpleAlert($content, $url = 'javascript:history.go(-1);')
    {
        echo "<SCRIPT language=JavaScript>alert('$content');</SCRIPT>";
        echo ' ';
        exit;
    }


    public function index(){
        $code=trim(I('get.code'));
        if(empty($code)){
            $this->simpleAlert('缺失参数code');
        }

        session::set('code',$code);
        $url=getBaseUrl().'/musihui/dropCard.php';
        redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx08981071f73cb701&redirect_uri=$url&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
    }

    /**
     * 接收openid写入缓存
     */
    public function getInfo(){
        $openid=trim(I('get.openid'));
        session::set('openid',$openid);
        redirect(U('doDrop'));
    }
    /**
     *显示卡券信息和核销
     */
    public function doDrop(){
        $code=session::get('code');
        $openid=session::get('openid');
        $adminid = D('AdminScan')->where(array('openid'=>$openid))->select();
        // $adminInfo=D('Admin')->where('id'=>$adminid)->find();
        if(empty($adminid)){
            $this->simpleAlert('非核销人员请勿扫码');
        }

        $getInfo=D('UserGetCard')->where(array('code'=>$code))->find();
        if(empty($getInfo)){
            $this->simpleAlert('未找到这个券的信息');
        }
        if($getInfo['status']!=0){
            $this->simpleAlert('卡券已失效');
        }

        $cardInfo=D('Card')->where(array('cardid'=>$getInfo['cardid']))->find();
        if($cardInfo['dropshop']!=0){
            //并非所有门店都能核销
            $count = 0;
            
            foreach ($adminid as $key => $value) {
                $adminInfo = D('Admin')->where(array('id'=>$value['adminid']))->find();
                if($adminInfo['shop']==$cardInfo['dropshop']){
                    $count = 1;
                    break;
                }
            }
            if($count==0){
                $this->simpleAlert('您没有权限核销此卡券');
            }
        }

        if($cardInfo['starttime']>time() || $cardInfo['endtime']<time()){
            $this->simpleAlert('卡券当前不在有效期');
        }

        //可以核销卡券，执行核销
        $getInfo['status']=1;
        $getInfo['consumetime']=time();
        $getInfo['consumeshop']=$adminInfo['shop'];
        $getInfo['consumetype']='scan';
        $getInfo['consumer']=$adminid[0]['nickname'];
        D('UserGetCard')->data($getInfo)->save();
        $this->simpleAlert('核销成功');


    }

}